package security;


import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.PortMapper;
import org.springframework.security.web.PortMapperImpl;
import org.springframework.security.web.PortResolver;
import org.springframework.security.web.PortResolverImpl;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;

public class MyAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint{
	private boolean forceHttps;
    private boolean useForward;
    private RedirectStrategy redirectStrategy;
    
    public MyAuthenticationEntryPoint(){
        forceHttps = false;
        useForward = false;
        redirectStrategy = new DefaultRedirectStrategy();
    }
	public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
	     throws IOException, ServletException
	 {
	     HttpServletRequest httpRequest = request;
	     HttpServletResponse httpResponse = response;
	     String scheme = request.getScheme();
	     
	     /**
	      * 把来源url 进行传送
	      */
	     String comeUrl = request.getRequestURL().toString();
	     
	     if(null != comeUrl)
	    	 request.getSession().setAttribute("spring-security-redirect", comeUrl);
	     String redirectUrl = null;
	     if(useForward)
	     {
	         if(forceHttps && "http".equals(request.getScheme()))
	             redirectUrl = buildHttpsRedirectUrlForRequest(httpRequest);
	         if(redirectUrl == null)
	         {
	             String loginForm = determineUrlToUseForThisRequest(httpRequest, httpResponse, authException);
	             RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(loginForm);
	             dispatcher.forward(request, response);
	             return;
	         }
	     } else
	     {
	         redirectUrl = buildRedirectUrlToLoginPage(httpRequest, httpResponse, authException);
	     }
	     redirectStrategy.sendRedirect(httpRequest, httpResponse, redirectUrl);
	 }
}
